#
# package_version_tool.py extracts the version number from package.xml
# and generates a headerfile sick_scan_xd_version.h defining that version.
#
# Usage example:
# python python/tools/package_version_tool.py --package_xml_file package.xml --cpp_header_path include/sick_scan/sick_scan_xd_version.h
#

import xml.etree.ElementTree as ET
import argparse

def extract_version_from_header(file_path):
    # Define the exact line keyword with version number
    search_keyword = '#define SICK_SCAN_XD_VERSION'

    # Open the header file and read line by line
    with open(file_path, 'r') as file:
        for line in file:
            # Ensure the line starts with the keyword including the version number
            if line.strip().startswith(search_keyword):
                # Extract the version number enclosed in quotes
                try:
                    version = line.split()[2]  # Split the line at the quotes and take the second element
                    return version
                except IndexError:
                    # Handle unexpected format
                    print("Version format in the file does not match expected format.")
    return ""

def parse_xml_and_generate_header(package_xml_file, cpp_header_path):
    # Parse the XML file
    tree = ET.parse(package_xml_file)
    root = tree.getroot()

    # Extract the version number from the <version> tag in package.xml
    package_version = root.find('version').text
    package_version = f'\"{package_version}\"'

    # Extract the version number from "define SICK_SCAN_XD_VERSION" in cpp_header_path
    header_version = extract_version_from_header(cpp_header_path)
    print(f"Found version {package_version} in file \"{package_xml_file}\" and version {header_version} in file \"{cpp_header_path}\"")

    if package_version != header_version:
        # Create a C++ header file content with the version defined and write to C++ header file
        cpp_header_content = f"#ifndef SICK_SCAN_XD_VERSION\n#define SICK_SCAN_XD_VERSION {package_version}\n#endif // SICK_SCAN_XD_VERSION\n"
        with open(cpp_header_path, 'w') as cpp_file:
            cpp_file.write(f'/* This file has been generated by package_version_tool.py. Do not edit this file. To provide a new version number, modify file package.xml and rebuild */\n')
            cpp_file.write(cpp_header_content)
        print(f"Generated file \"{cpp_header_path}\" with version {package_version}")
    else:
        print(f"Found identical versions, leaving file \"{cpp_header_path}\" unmodified")


def main():
    parser = argparse.ArgumentParser(description="Parse XML to extract the version and generate a C++ header file.")
    parser.add_argument('--package_xml_file', type=str, default='package.xml', help='Path to the package.xml file.')
    parser.add_argument('--cpp_header_path', type=str, default='include/sick_scan/sick_scan_xd_version.h', help='Path to save the C++ header file.')

    args = parser.parse_args()

    parse_xml_and_generate_header(args.package_xml_file, args.cpp_header_path)

if __name__ == '__main__':
    main()
